package com.mayikt.service.impl;

import com.mayikt.entity.PayTokenLogEntity;
import com.mayikt.mapper.PayTokenLogMapper;
import com.mayikt.service.PayTokenService;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.dto.req.PayOrderTokenDto;
import com.mayikt.entity.PaymentTransactionEntity;
import com.mayikt.mapper.PaymentTransactionMapper;
import com.mayikt.utils.SnowflakeIdUtils;
import com.mayikt.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PayTokenServiceImpl extends BaseApiService implements PayTokenService {
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private PayTokenLogMapper payTokenLogMapper;

    @Override
    public BaseResponse<String> toPayOrderToken(PayOrderTokenDto payOrderTokenDto) {
        // 1.验证参数
        String orderId = payOrderTokenDto.getOrderId();
        if (StringUtils.isEmpty(orderId)) {
            return setResultError("订单号码不能为空!");
        }
        Long payAmount = payOrderTokenDto.getPayAmount();
        if (payAmount == null) {
            return setResultError("金额不能为空!");
        }
        Long userId = payOrderTokenDto.getUserId();
        if (userId == null) {
            return setResultError("userId不能为空!");
        }
        String orderName = payOrderTokenDto.getOrderName();
        if (orderName == null) {
            return setResultError("orderName不能为空!");
        }
        // 2.生成支付的全局的id
        PaymentTransactionEntity paymentTransactionEntity =
                dtoToDo(payOrderTokenDto, PaymentTransactionEntity.class);
        // 3.向支付详细表插入一条记录
        String paymentId = SnowflakeIdUtils.nextId();
        paymentTransactionEntity.setPaymentId(paymentId);
        int result = paymentTransactionMapper.insertPaymentTransaction(paymentTransactionEntity);
        if (result <= 0) {
            return setResultError("系统错误");
        }
        Long payId = paymentTransactionEntity.getId();
        if (payId == null) {
            return setResultError("系统错误");
        }
        // 4.生成token令牌
        String payToken = tokenUtil.createToken("mayikt:pay", payId + "", 10L);
        if (StringUtils.isEmpty(payToken)) {
            return setResultError("生成支付令牌失败");
        }
        PayTokenLogEntity payTokenLogEntity = new PayTokenLogEntity(payToken, paymentId);
        payTokenLogMapper.insertPayTokenLog(payTokenLogEntity);
        return setResultSuccess(payToken);
    }
}
